<template>
  <div class="page_applyStock">
    <van-nav-bar
      :title="`${eachStockObj.stockName}的股份申请`"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form @submit="onSubmit" @failed="onFail" ref="apply_form">
      <van-field autocomplete="off"
        v-model="apply_content"
        name="apply_content"
        rows="4"
        autosize
        label="申请理由"
        type="textarea"
        placeholder="请输入申请理由"
        required
        :rules="rules"
      />
      <van-field autocomplete="off"
        v-model="witness_name"
        name="witness_name"
        label="证明人姓名"
        placeholder="请输入证明人姓名"
        :rules="rules"
        required
      />
      <van-field autocomplete="off"
        v-model="witness_phone"
        name="witness_phone"
        type="number"
        label="证明人手机号"
        placeholder="请输入证明人手机号"
        maxlength="11"
        :rules="[
          {
            required: true,
            message: '请输入!'
          },
          {
            pattern: /^1\d{10}$/,
            message: '请正确填写手机号!'
          }
        ]"
        required
      />
      <van-field autocomplete="off"
        v-model="ideal_market_price"
        name="ideal_market_price"
        type="number"
        label="理想市场价"
        placeholder="请输入理想的市场价值"
        :rules="[
          { required: true, message: '请填写' },
          {
            pattern: /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/,
            message: '最多带两位小数'
          },
        ]"
        required
      >
        <template #button>
          <van-tag type="danger">元</van-tag>
        </template>
      </van-field>

      <van-field autocomplete="off" name="witness_photos"
                 label="上传图片"
      >
        <template #input>
          <van-uploader
            v-model="witness_photos"
            :max-count="9"
            :after-read="uploadPhotoList_witness"
            :preview-options="{
              closeable: true,
            }"
            @delete="toDeleteAnyPreviewPhoto_witness"
            :max-size="10 * 1024 * 1024"
            @oversize="onOversize"
          />
        </template>
      </van-field>


      <div style="margin: 16px;" v-if="!isChecked">
        <van-checkbox v-model="isChecked" :bind-group="false">
          <div>
            <span>我已阅读并同意以下协议:</span>
            <u @click.stop="applyOrStockEquityAgreement('apply')" style="color: #1989fa">《申请条件协议》</u> 和
            <u @click.stop="applyOrStockEquityAgreement('stockEquity')" style="color: #1989fa ">《股东权益义务协议》</u>
          </div>
        </van-checkbox>
      </div>

      <div style="margin: 16px;" v-if="!isChecked">
        <van-button round block type="info"
                    native-type="button"
                    disabled
        >请先勾选协议</van-button>
      </div>

      <DebounceSubmitBtn
        v-else
        :isSubmitBtnDisabled="isSubmitBtnDisabled"
      />
    </van-form>

  </div>
</template>

<script>

import {Toast, Dialog} from 'vant'
import stock from "../../../api/stock";
import {mapGetters} from "vuex";
import {cosUploadImg} from '@/utils/cosUpload.js';

import DebounceSubmitBtn from "../../../components/DebounceSubmitBtn";
import {mixin_btnStatus} from "../../../mixin/mixin_btn";

const rules = [
  { required: true, message: '请填写' }
];


export default {
  name: 'applyStock',
  mixins: [mixin_btnStatus],
  components: {
    DebounceSubmitBtn,
  },
  data(){
    return {
      rules,
      eachStockObj: JSON.parse(this.$route.query.eachStockObj),
      apply_content: '',
      witness_name: '',
      witness_phone: '',
      ideal_market_price: '',
      isChecked: true,
      witness_photos: [],
      // 多个图片
      witness_photos_list_url: [],
      radio: '1',
    }
  },

  computed: {
    ...mapGetters(['allUserInfo']),
  },
  methods: {
    // 封装公共的上传图片函数
    async _reqUploadPicture_apply(picture) {
      let formData = new FormData()
      formData.append('filename', picture.file)
      // 图片归属文件夹
      const img_type = 'stock_img'
      // const res = await this.$api.uploadImg.uploadPhotos(formData, img_type)
      const res = await cosUploadImg(picture.file, img_type)
      if (res.code === 200) {
        return res.data
      }
    },

    async onSubmit(values) {
      console.log('submit提交', values);
      if(!this.isChecked){
        Toast('请先勾选协议!');
        return null
      };

      if(values.ideal_market_price*1 <= 0){
        Toast('市场价输入有误, 必须大于0!');
        return null
      };

      if (this.allUserInfo.certification_state === 2){
        this._updateSubmitBtnStatus();
        const {apply_content, ideal_market_price, witness_name, witness_phone, witness_photos} = values;
        const paramObj = {
          stockid: this.eachStockObj.stockid,
          reason: apply_content,
          price: ideal_market_price,
          witness: witness_name,
          witnessmobile: witness_phone,
          imgurl: this.witness_photos_list_url.join("|"),
        };
        const resp = await this.$api.stock.reqApplyStock(paramObj);
        if (resp.code === 200) {
          // 重置表单
          // this.$refs.apply_form.resetValidation();

          Dialog.alert({
            title: '申请成功',
            message: '点击返回, 可在 【股份申请审核记录】下的【我的申请记录】查看!',
            messageAlign: 'left',
          }).then(() => {
            // on close
            this.$router.back();
          });
        }
      } else {
        Dialog.confirm({
          title: '个人认证还没完成！！',
          message: '当前操作需完成个人认证！你当前还没有完成个人认证，请点击去个人认证。',
          messageAlign: 'left',
          confirmButtonText: '前往个人认证'
        }).then(() => {
          this.$router.push('/personalAuth')
        })
          .catch(() => {
            // on cancel
          })
      }
    },

    onFail(values, errors){
      if(!this.isChecked){
        Toast('请先勾选协议!')
      }
    },

    // 上传图片
    uploadPhotoList_witness(picture) {
      picture.status = 'uploading';
      picture.message = '上传中...';
      this._reqUploadPicture_apply(picture).then(url => {
        if (!url) {
          Toast('图片上传失败!')
          picture.status = 'failed';
          picture.message = '上传失败';
        } else {
          picture.status = 'done';
        }

        // 不断的增加
        this.witness_photos_list_url.push(url)
      })
    },

    // 删除文件预览时，修改数据
    toDeleteAnyPreviewPhoto_witness(file, detail) {
      if (this.witness_photos_list_url.length === 0) {
        this.witness_photos_list_url = []
      } else {
        // splice方法会改变原始数组
        this.witness_photos_list_url.splice(detail.index, 1)
      }
    },

    onOversize(){
      Toast('文件大小不能超过 10M!');
    },

    applyOrStockEquityAgreement(keyword){
      if(keyword){
        this.$router.push({
          name: 'allAgreement',
          query: {
            keyword,
          }
        })
      }

    },



  },


};
</script>


<style>

</style>
